import pyaudio
import sys
import time

class AudioDeviceFixer:
    def __init__(self):
        self.audio = None
        self.initialize_pyaudio()
    
    def initialize_pyaudio(self):
        """安全初始化PyAudio"""
        try:
            self.audio = pyaudio.PyAudio()
            print("✅ PyAudio初始化成功")
        except Exception as e:
            print(f"❌ PyAudio初始化失败: {e}")
            self.audio = None
    
    def list_all_devices(self):
        """列出所有音频设备"""
        if not self.audio:
            print("PyAudio未初始化")
            return []
        
        print("=== 系统音频设备列表 ===")
        devices = []
        device_count = self.audio.get_device_count()
        
        for i in range(device_count):
            try:
                info = self.audio.get_device_info_by_index(i)
                devices.append(info)
                
                status = "✅" if info['maxInputChannels'] > 0 or info['maxOutputChannels'] > 0 else "❌"
                print(f"{status} 设备 {i}: {info['name']}")
                print(f"   输入通道: {info['maxInputChannels']}")
                print(f"   输出通道: {info['maxOutputChannels']}")
                print(f"   默认采样率: {info['defaultSampleRate']}")
                print(f"   主机API: {info['hostApi']}")
                print("-" * 50)
                
            except Exception as e:
                print(f"❌ 获取设备 {i} 信息失败: {e}")
        
        return devices
    
    def find_working_devices(self):
        """查找可用的音频设备"""
        working_input_devices = []
        working_output_devices = []
        
        if not self.audio:
            return working_input_devices, working_output_devices
        
        device_count = self.audio.get_device_count()
        
        for i in range(device_count):
            try:
                info = self.audio.get_device_info_by_index(i)
                
                # 测试输入设备
                if info['maxInputChannels'] > 0:
                    if self.test_input_device(i):
                        working_input_devices.append((i, info))
                
                # 测试输出设备
                if info['maxOutputChannels'] > 0:
                    working_output_devices.append((i, info))
                    
            except Exception as e:
                continue
        
        print(f"找到 {len(working_input_devices)} 个可用输入设备")
        print(f"找到 {len(working_output_devices)} 个可用输出设备")
        
        return working_input_devices, working_output_devices
    
    def test_input_device(self, device_index):
        """测试输入设备是否可用"""
        try:
            # 尝试打开设备进行短暂录音测试
            stream = self.audio.open(
                format=pyaudio.paFloat32,
                channels=1,
                rate=44100,
                input=True,
                input_device_index=device_index,
                frames_per_buffer=1024
            )
            
            # 读取一小段数据
            data = stream.read(1024)
            stream.stop_stream()
            stream.close()
            
            print(f"✅ 输入设备 {device_index} 测试通过")
            return True
            
        except Exception as e:
            print(f"❌ 输入设备 {device_index} 测试失败: {e}")
            return False
    
    def get_default_devices(self):
        """获取默认设备"""
        if not self.audio:
            return None, None
        
        try:
            default_input = self.audio.get_default_input_device_info()
            print(f"默认输入设备: {default_input['name']} (索引: {default_input['index']})")
        except Exception as e:
            print(f"❌ 获取默认输入设备失败: {e}")
            default_input = None
        
        try:
            default_output = self.audio.get_default_output_device_info()
            print(f"默认输出设备: {default_output['name']} (索引: {default_output['index']})")
        except Exception as e:
            print(f"❌ 获取默认输出设备失败: {e}")
            default_output = None
        
        return default_input, default_output
    
    def fix_audio_issues(self):
        """修复音频问题"""
        print("🔧 开始诊断音频问题...")
        
        # 1. 检查设备列表
        devices = self.list_all_devices()
        if not devices:
            print("❌ 没有检测到任何音频设备")
            return None
        
        # 2. 获取默认设备
        default_input, default_output = self.get_default_devices()
        
        # 3. 查找可用设备
        working_inputs, working_outputs = self.find_working_devices()
        
        # 4. 推荐解决方案
        recommendations = self.generate_recommendations(
            devices, default_input, default_output, 
            working_inputs, working_outputs
        )
        
        return recommendations
    
    def generate_recommendations(self, devices, default_input, default_output, 
                               working_inputs, working_outputs):
        """生成修复建议"""
        recommendations = {
            'status': 'unknown',
            'issues': [],
            'solutions': [],
            'recommended_devices': {}
        }
        
        # 检查问题
        if not default_input and not default_output:
            recommendations['issues'].append("没有默认音频设备")
            recommendations['solutions'].append("请检查音频驱动程序")
        
        if not working_inputs:
            recommendations['issues'].append("没有可用的输入设备")
            recommendations['solutions'].append("请检查麦克风连接和权限")
        
        if not working_outputs:
            recommendations['issues'].append("没有可用的输出设备")
            recommendations['solutions'].append("请检查扬声器/耳机连接")
        
        # 推荐设备
        if working_inputs:
            best_input = working_inputs[0]  # 选择第一个可用的
            recommendations['recommended_devices']['input'] = {
                'index': best_input[0],
                'name': best_input[1]['name']
            }
        
        if working_outputs:
            best_output = working_outputs[0]
            recommendations['recommended_devices']['output'] = {
                'index': best_output[0], 
                'name': best_output[1]['name']
            }
        
        # 确定整体状态
        if working_inputs and working_outputs:
            recommendations['status'] = 'good'
        elif working_inputs or working_outputs:
            recommendations['status'] = 'partial'
        else:
            recommendations['status'] = 'bad'
        
        return recommendations
    
    def __del__(self):
        """清理资源"""
        if self.audio:
            self.audio.terminate()

# 使用示例
if __name__ == "__main__":
    fixer = AudioDeviceFixer()
    recommendations = fixer.fix_audio_issues()
    
    if recommendations:
        print("\n=== 修复建议 ===")
        print(f"状态: {recommendations['status']}")
        
        if recommendations['issues']:
            print("\n发现的问题:")
            for issue in recommendations['issues']:
                print(f"  ❌ {issue}")
        
        if recommendations['solutions']:
            print("\n建议解决方案:")
            for solution in recommendations['solutions']:
                print(f"  🔧 {solution}")
        
        if recommendations['recommended_devices']:
            print("\n推荐设备:")
            for device_type, device_info in recommendations['recommended_devices'].items():
                print(f"  {device_type}: {device_info['name']} (索引: {device_info['index']})")